import {OperationType, RequestMethod} from "../utils";
import path from "path";
import {Response} from "express";
import {getDate, formatTime, isJson, saveFileData, getFileData} from "../utils";

const fs = require("fs");

export interface RecordObj {
  operator: string,
  operatorId: any,
  operationTime?: string,
  operationType?: string,
  requestMethod?: string,
  oldRecord?: any | null,
  newRecord?: any | null,
}

export const createRecordObj = (data: RecordObj): RecordObj => {
  const {operator, operatorId, operationType, requestMethod, oldRecord, newRecord} = data;
  return {
    operator,
    operatorId,
    operationTime: formatTime(Date.now()),
    operationType: operationType ?? OperationType.CREATE,
    requestMethod: requestMethod ?? RequestMethod.GET,
    newRecord,
    oldRecord
  };
};

const createRecordPath = (recordModel: string) => {
  return path.resolve(process.cwd(), `./src/record/${recordModel}.json`);
};

export const createRecord = async (recordModel: string, data: RecordObj, res?: any) => {
  const filePath = createRecordPath(recordModel);
  if (!fs.existsSync(filePath)) {
    // 没有文件，直接写入数据
    const dataStr = handleRecordData(recordModel, data);
    await saveFileData(filePath, dataStr, res);
    return;
  }
  const fileData = await getFileData(filePath) as string;

  const dataStr = handleRecordData(recordModel, data, fileData);
  await saveFileData(filePath, dataStr, res);
  return;
};

const handleRecordData = (recordModel: string, newData: RecordObj, oldData?: string): string => {
  return formatWriteData(recordModel, newData as RecordObj, oldData);
};

const formatWriteData = (recordModel: string, newData: RecordObj, oldData?: string) => {
  let jsonObj: any;
  const date = getDate();
  if (!oldData) {
    jsonObj = {};
  } else {
    jsonObj = isJson(oldData) ? JSON.parse(oldData) : {};
  }
  if (!jsonObj[recordModel])
    jsonObj[recordModel] = {};
  if (!jsonObj[recordModel][date])
    jsonObj[recordModel][date] = [];

  jsonObj[recordModel][date].push(newData);
  return JSON.stringify(jsonObj);
};


export class ReadOrWriteError {
  constructor(public message: string, public res?: Response) {
  }
}
